/*
 * Copyright (C) 2010-2101 Alibaba Group Holding Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.otter.manager.biz.config.datacolumnpair.impl;

import com.alibaba.fastjson.TypeReference;
import com.alibaba.otter.manager.biz.common.exceptions.ManagerException;
import com.alibaba.otter.manager.biz.common.exceptions.RepeatConfigureException;
import com.alibaba.otter.manager.biz.dto.CommonSearchDTO;
import com.alibaba.otter.manager.biz.config.datacolumnpair.DataColumnPairGroupService;
import com.alibaba.otter.manager.biz.config.datacolumnpair.DataColumnPairService;
import com.alibaba.otter.manager.biz.config.datacolumnpair.dal.DataColumnPairGroupDao;
import com.alibaba.otter.manager.biz.config.datacolumnpair.dal.dataobject.ColumnPairGroupDO;
import com.alibaba.otter.shared.common.model.config.data.ColumnGroup;
import com.alibaba.otter.shared.common.model.config.data.ColumnPair;
import com.alibaba.otter.shared.common.utils.Assert;
import com.alibaba.otter.shared.common.utils.JsonUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Instant;
import java.util.*;

/**
 * @author simon 2012-4-20 下午4:11:32
 */
@Service
public class DataColumnPairGroupServiceImpl implements DataColumnPairGroupService {

    private static final Logger logger = LoggerFactory.getLogger(DataColumnPairGroupServiceImpl.class);

    private final DataColumnPairGroupDao dataColumnPairGroupDao;

    private final DataColumnPairService dataColumnPairService;

    public DataColumnPairGroupServiceImpl(DataColumnPairGroupDao dataColumnPairGroupDao, DataColumnPairService dataColumnPairService) {
        this.dataColumnPairGroupDao = dataColumnPairGroupDao;
        this.dataColumnPairService = dataColumnPairService;
    }

    @Override
    public void create(ColumnGroup entityObj) {
        Assert.assertNotNull(entityObj);

        try {
            ColumnPairGroupDO columnPairGroupDo = modelToDo(entityObj);
            dataColumnPairGroupDao.uniqueInsert(columnPairGroupDo);
        } catch (RepeatConfigureException rcf) {
            throw rcf;
        } catch (Exception e) {
            logger.error("ERROR ## create dataColumnPairGroup has an exception!");
            throw new ManagerException(e);
        }
    }

    @Override
    public List<ColumnGroup> listByDataMediaPairId(Long dataMediaPairId) {
        Assert.assertNotNull(dataMediaPairId);
        List<ColumnPairGroupDO> columnPairGroupDos = dataColumnPairGroupDao.ListByDataMediaPairId(dataMediaPairId);
        if (CollectionUtils.isEmpty(columnPairGroupDos)) {
            return new ArrayList<>();
        }

        return doToModel(columnPairGroupDos);
    }

    @Override
    public Map<Long, List<ColumnGroup>> listByDataMediaPairIds(Long... dataMediaPairIds) {
        Assert.assertNotNull(dataMediaPairIds);
        Map<Long, List<ColumnGroup>> dataColumnGroups = new HashMap<>();
        try {
            List<ColumnPairGroupDO> columnPairGroupDos = dataColumnPairGroupDao.ListByDataMediaPairIds(dataMediaPairIds);
            if (CollectionUtils.isEmpty(columnPairGroupDos)) {
                logger.debug("DEBUG ## couldn't query any dataColumnPairGroup, maybe hasn't create any dataColumnPairGroup.");
                return dataColumnGroups;
            }

            for (ColumnPairGroupDO columnPairGroupDo : columnPairGroupDos) {
                List<ColumnGroup> columnGroups = dataColumnGroups.get(columnPairGroupDo.getDataMediaPairId());
                if (columnGroups != null) {
                    if (!columnGroups.contains(doToModel(columnPairGroupDo))) {
                        columnGroups.add(doToModel(columnPairGroupDo));
                    }
                } else {
                    columnGroups = new ArrayList<>();
                    columnGroups.add(doToModel(columnPairGroupDo));
                    dataColumnGroups.put(columnPairGroupDo.getDataMediaPairId(), columnGroups);
                }
            }
        } catch (Exception e) {
            logger.error("ERROR ## query dataColumnPairGroup by dataMediaId:{} has an exception!", Arrays.toString(dataMediaPairIds));
            throw new ManagerException(e);
        }

        return dataColumnGroups;
    }

    @Override
    public Page<ColumnGroup> dataColumnPairGroupPage(CommonSearchDTO searchVo, Pageable pageable) {
        Page<ColumnPairGroupDO> pagedList = dataColumnPairGroupDao.dataColumnPairGroupPage(searchVo,pageable);
        return pagedList.map(this::doToModel);
    }

    @Override
    public void remove(Long identity) {

    }

    @Override
    public void removeByDataMediaPairId(Long dataMediaPairId) {
        Assert.assertNotNull(dataMediaPairId);
        dataColumnPairGroupDao.deleteByDataMediaPairId(dataMediaPairId);
    }

    @Override
    public void modify(ColumnGroup entityObj) {

    }

    @Override
    public ColumnGroup findById(Long identity) {
        ColumnPairGroupDO columnPairGroupDO = dataColumnPairGroupDao.selectOneById(identity);
        return this.doToModel(columnPairGroupDO);
    }

    @Override
    public List<ColumnGroup> listByIds(Long... identities) {
        return null;
    }

    @Override
    public List<ColumnGroup> listAll() {
        return null;
    }

    @Override
    public List<ColumnGroup> listByCondition(Map condition) {
        return null;
    }

    @Override
    public long getCount() {
        return dataColumnPairGroupDao.selectCountByQuery(QueryWrapper.create());
    }

    @Override
    public long getCount(Map<String,Object> condition) {
        return dataColumnPairGroupDao.selectCountByQuery(QueryWrapper.create(condition));
    }

    /*-------------------------------------------------------------*/

    /**
     * 用于DO对象转化为Model对象
     */
    private ColumnGroup doToModel(ColumnPairGroupDO columnPairGroupDo) {
        ColumnGroup columnGroup = new ColumnGroup();
        columnGroup.setId(columnPairGroupDo.getId());
        List<ColumnPair> columnPairs = new ArrayList<ColumnPair>();
        if (StringUtils.isNotBlank(columnPairGroupDo.getColumnPairContent())) {
            columnPairs = JsonUtils.unmarshalFromString(columnPairGroupDo.getColumnPairContent(),
                    new TypeReference<ArrayList<ColumnPair>>() {
                    });
        }

        columnGroup.setColumnPairs(columnPairs);
        columnGroup.setDataMediaPairId(columnPairGroupDo.getDataMediaPairId());
        columnGroup.setGmtCreate(Date.from(columnPairGroupDo.getGmtCreate()));
        columnGroup.setGmtModified(Date.from(columnPairGroupDo.getGmtModified()));

        return columnGroup;
    }

    private List<ColumnGroup> doToModel(List<ColumnPairGroupDO> columnPairGroupDos) {
        List<ColumnGroup> columnGroups = new ArrayList<>();
        for (ColumnPairGroupDO columnPairGroupDO : columnPairGroupDos) {
            columnGroups.add(doToModel(columnPairGroupDO));
        }

        return columnGroups;
    }

    /**
     * 用于Model对象转化为DO对象
     *
     * @return DataMediaPairDO
     */
    private ColumnPairGroupDO modelToDo(ColumnGroup columnGroup) {
        ColumnPairGroupDO columnPairGroupDo = new ColumnPairGroupDO();
        columnPairGroupDo.setId(columnGroup.getId());
        columnPairGroupDo.setColumnPairContent(JsonUtils.marshalToString(columnGroup.getColumnPairs()));
        columnPairGroupDo.setDataMediaPairId(columnGroup.getDataMediaPairId());
        columnPairGroupDo.setGmtCreate(Instant.now());
        columnPairGroupDo.setGmtModified(Instant.now());

        return columnPairGroupDo;
    }




}
